package com.sgy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 本地浏览器相关操作
 *
 * @author shenguangyang
 * @date 2022-08-14 0:45
 */
public class Browse {
    private static final Logger log = LoggerFactory.getLogger(Browse.class);
    private static final Map<String, Long> openRecord = new ConcurrentHashMap<>();
    /** 打开同一个页面的周期, 3s之内不能重复打卡 */
    private static final Long MAX_OPEN_PERIOD = 3000L;
    static {
        System.setProperty("java.awt.headless", "false");
    }

    public static void openUrl(String url) {
        try {
            // 在一段时间内不能重复打开
            Long preTime = openRecord.get(url);
            if (preTime == null) {
                synchronized (url.intern()) {
                    preTime = openRecord.get(url);
                    if (preTime == null) {
                        preTime = System.currentTimeMillis();
                        openRecord.put(url, preTime);
                        doOpen(url);
                        return;
                    }
                }
            }
            if (Math.abs(System.currentTimeMillis() - preTime)  > MAX_OPEN_PERIOD) {
                openRecord.put(url, System.currentTimeMillis());
            } else {
                openRecord.put(url, System.currentTimeMillis());
                return;
            }

            doOpen(url);

        } catch (java.lang.NullPointerException e) {
            // 此为uri为空时抛出异常
            e.printStackTrace();
        } catch (Exception e) {
            log.error("error: " + e);
        }
    }

    private static void doOpen(String url) {
        // 获取当前系统桌面扩展
        try {
            Desktop dp = Desktop.getDesktop();
            URI uri = URI.create(url);

            // 判断系统桌面是否支持要执行的功能
            if (dp.isSupported(Desktop.Action.BROWSE)) {
                // 获取系统默认浏览器打开链接
                dp.browse(uri);
            }

        } catch (java.lang.NullPointerException e) {
            // 此为uri为空时抛出异常
            e.printStackTrace();
        } catch (java.io.IOException e) {
            // 此为无法获取系统默认浏览器
           log.error("error: " +  e);
        }
    }
}
